//加载express 
const express = require('express');
//实例路由 
const router = express.Router();
//导入数据模型 
const {address} = require('../model/db')
//===============API写下面================================================ 
// 添加保存修改地址
router.post('/wxAddressSave', async (req, res) => {
    //console.log(req.body) 
    try {
        const {openid,isDefault,_id} = req.body;
        if (isDefault) {
            await address.updateOne({
                openid,isDefault
            }, {isDefault: false})
        } 
        if (_id) {
            //id存在，则修改地址信息 
            await address.findByIdAndUpdate(_id, req.body)
        } else {
            //id不存在，执行添加操作 
            await address.create(req.body);
        }
        res.send({
            status: 'success'
        })
    } catch (error) {
        console.log(error)
        res.send({
            status: 'err'
        })
    }
})
//小程序端 获取地址列表 
router.get('/wxAddress', async (req, res) => {
    try {
        const addressList = await address.find({
            openid: req.query.openid
        }).sort({
            addTime: -1
        });
        res.send({
            message: 'success',
            result: addressList
        });
    } catch (err) {
        res.send({
            message: 'fail',
            result: err
        })
    }
})
//小程序端删除地址 
router.get('/wxDelAddress', async (req, res) => {
    try {
        const {
            _id
        } = req.query
        await address.findByIdAndDelete(_id)
        res.send('success')
    } catch (error) {
        console.log(error)
        res.send('fail')
    }
})

//===============API写在上面============================================= 
//导出路由 
module.exports = router;